// pages/profile/advice/chat/chat.js
Page({
  data: {
    doctorId: null,
    consultationId: null,
    doctor: null,
    messages: [],
    inputText: '',
    isTyping: false,
    scrollToBottom: true,
    consultationStatus: 'pending'
  },

  onLoad(options) {
    if (options.doctorId && options.consultationId) {
      this.setData({ 
        doctorId: parseInt(options.doctorId),
        consultationId: parseInt(options.consultationId)
      });
      this.loadDoctorInfo();
      this.loadMessages();
    }
  },

  onShow() {
    // 页面显示时滚动到底部
    this.scrollToBottom();
  },

  // 加载医生信息
  loadDoctorInfo() {
    // 模拟医生数据
    const doctor = {
      id: this.data.doctorId,
      name: '王医生',
      title: '主任医师',
      department: '营养科',
      hospital: '市人民医院',
      avatar: '/assets/images/doctor-avatar.jpg',
      status: 'online',
      responseTime: '5分钟内'
    };
    
    this.setData({ doctor });
    
    // 设置导航栏标题
    wx.setNavigationBarTitle({
      title: `与${doctor.name}的对话`
    });
  },

  // 加载消息列表
  loadMessages() {
    // 模拟消息数据
    const messages = [
      {
        id: 1,
        type: 'text',
        content: '您好，我是王医生，请问有什么可以帮助您的吗？',
        sender: 'doctor',
        time: '2024-01-15 09:00',
        read: true
      },
      {
        id: 2,
        type: 'text',
        content: '医生您好，我最近血糖有点高，应该怎么调整饮食？',
        sender: 'patient',
        time: '2024-01-15 09:05',
        read: true
      },
      {
        id: 3,
        type: 'text',
        content: '建议您减少精制碳水化合物的摄入，增加蔬菜和蛋白质的比例。具体来说：\n\n1. 早餐可以选择燕麦粥配鸡蛋\n2. 午餐多吃青菜，少吃米饭\n3. 晚餐以蔬菜汤为主',
        sender: 'doctor',
        time: '2024-01-15 09:10',
        read: true
      },
      {
        id: 4,
        type: 'text',
        content: '好的，我会按照您的建议调整。还有其他的注意事项吗？',
        sender: 'patient',
        time: '2024-01-15 09:15',
        read: true
      },
      {
        id: 5,
        type: 'text',
        content: '另外建议您：\n• 每天定时测量血糖\n• 适量运动，如散步30分钟\n• 保持充足睡眠\n• 定期复查',
        sender: 'doctor',
        time: '2024-01-15 09:20',
        read: true
      }
    ];

    this.setData({ 
      messages,
      consultationStatus: 'active'
    });
    this.scrollToBottom();
  },

  // 输入文本
  onInputChange(e) {
    this.setData({ inputText: e.detail.value });
  },

  // 发送消息
  sendMessage() {
    const { inputText, doctorId, consultationId } = this.data;
    
    if (!inputText.trim()) {
      wx.showToast({
        title: '请输入消息内容',
        icon: 'none'
      });
      return;
    }

    // 添加患者消息
    const newMessage = {
      id: Date.now(),
      type: 'text',
      content: inputText.trim(),
      sender: 'patient',
      time: this.formatTime(new Date()),
      read: true
    };

    this.setData({
      messages: [...this.data.messages, newMessage],
      inputText: '',
      isTyping: true
    });

    // 滚动到底部
    this.scrollToBottom();

    // 模拟医生回复
    setTimeout(() => {
      this.simulateDoctorReply();
    }, 2000);
  },

  // 模拟医生回复
  simulateDoctorReply() {
    const replies = [
      '好的，我明白了',
      '建议您继续观察，如有异常请及时联系',
      '这个情况需要进一步检查',
      '请按照我的建议执行，定期复查',
      '还有其他问题吗？'
    ];

    const randomReply = replies[Math.floor(Math.random() * replies.length)];
    
    const doctorMessage = {
      id: Date.now() + 1,
      type: 'text',
      content: randomReply,
      sender: 'doctor',
      time: this.formatTime(new Date()),
      read: true
    };

    this.setData({
      messages: [...this.data.messages, doctorMessage],
      isTyping: false
    });

    this.scrollToBottom();
  },

  // 发送图片
  sendImage() {
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        const tempFilePath = res.tempFilePaths[0];
        
        // 这里可以上传图片到服务器
        const newMessage = {
          id: Date.now(),
          type: 'image',
          content: tempFilePath,
          sender: 'patient',
          time: this.formatTime(new Date()),
          read: true
        };

        this.setData({
          messages: [...this.data.messages, newMessage]
        });

        this.scrollToBottom();
      }
    });
  },

  // 发送语音
  sendVoice() {
    wx.showToast({
      title: '语音功能开发中',
      icon: 'none'
    });
  },

  // 查看医生详情
  viewDoctorDetail() {
    wx.navigateTo({
      url: `/pages/profile/advice/doctorDetail/doctorDetail?id=${this.data.doctorId}`
    });
  },

  // 结束咨询
  endConsultation() {
    wx.showModal({
      title: '结束咨询',
      content: '确定要结束本次咨询吗？',
      success: (res) => {
        if (res.confirm) {
          this.setData({ consultationStatus: 'completed' });
          wx.showToast({
            title: '咨询已结束',
            icon: 'success'
          });
          
          // 跳转到评价页面
          setTimeout(() => {
            wx.navigateTo({
              url: `/pages/profile/advice/rating/rating?consultationId=${this.data.consultationId}`
            });
          }, 1500);
        }
      }
    });
  },

  // 发送快速回复
  sendQuickReply(e) {
    const content = e.currentTarget.dataset.content;
    this.setData({ inputText: content });
    this.sendMessage();
  },

  // 滚动到底部
  scrollToBottom() {
    setTimeout(() => {
      wx.pageScrollTo({
        scrollTop: 99999,
        duration: 300
      });
    }, 100);
  },

  // 格式化时间
  formatTime(date) {
    const year = date.getFullYear();
    const month = date.getMonth() + 1;
    const day = date.getDate();
    const hour = date.getHours();
    const minute = date.getMinutes();

    return `${year}-${month.toString().padStart(2, '0')}-${day.toString().padStart(2, '0')} ${hour.toString().padStart(2, '0')}:${minute.toString().padStart(2, '0')}`;
  },

  // 预览图片
  previewImage(e) {
    const src = e.currentTarget.dataset.src;
    wx.previewImage({
      urls: [src]
    });
  },

  // 长按消息
  longPressMessage(e) {
    const messageId = e.currentTarget.dataset.id;
    wx.showActionSheet({
      itemList: ['复制', '删除'],
      success: (res) => {
        if (res.tapIndex === 0) {
          // 复制消息
          wx.setClipboardData({
            data: e.currentTarget.dataset.content
          });
        } else if (res.tapIndex === 1) {
          // 删除消息
          this.deleteMessage(messageId);
        }
      }
    });
  },

  // 删除消息
  deleteMessage(messageId) {
    wx.showModal({
      title: '确认删除',
      content: '确定要删除这条消息吗？',
      success: (res) => {
        if (res.confirm) {
          const messages = this.data.messages.filter(msg => msg.id !== messageId);
          this.setData({ messages });
        }
      }
    });
  },

  // 拨打电话
  callDoctor() {
    wx.showModal({
      title: '联系医生',
      content: `是否拨打${this.data.doctor.name}的电话？`,
      success: (res) => {
        if (res.confirm) {
          wx.makePhoneCall({
            phoneNumber: '400-xxx-xxxx',
            fail: () => {
              wx.showToast({
                title: '拨号失败',
                icon: 'none'
              });
            }
          });
        }
      }
    });
  }
})
